package com.zz.push.client;

import com.zz.push.message.client.ConnectMessage;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springside.modules.mapper.JsonMapper;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

public class PushClientHandler extends SimpleChannelInboundHandler<String> {

    private static Logger logger = LoggerFactory.getLogger(PushClientChannelInitializer.class);

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
        Map map = JsonMapper.nonEmptyMapper().fromJson(msg, HashMap.class);

        int code = (int) map.get("code");
        switch (code) {
            case 10001:
                Long currentDate = (Long) map.get("currentDate");
                logger.info(new DateTime(currentDate).toString("yyyy-MM-dd HH:mm:ss"));
                break;
            default:
                break;
        }

        logger.info(msg);
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        ConnectMessage connectMessage = new ConnectMessage();
        connectMessage.setCode(10000);
        connectMessage.setMac("00:00:00:00:00:00");
        ctx.channel().writeAndFlush(JsonMapper.nonDefaultMapper().toJson(connectMessage) + "\r\n");
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        /*心跳处理*/
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent event = (IdleStateEvent) evt;
            if (event.state() == IdleState.READER_IDLE) {
                /*读超时*/
                logger.info("READER_IDLE 读超时");
                ctx.disconnect();
            } else if (event.state() == IdleState.WRITER_IDLE) {
                /*写超时*/
                logger.info("WRITER_IDLE 写超时");
            } else if (event.state() == IdleState.ALL_IDLE) {
                /*总超时*/
                logger.info("ALL_IDLE 总超时");
            }
        } else {
            super.userEventTriggered(ctx, evt);
        }
    }

    @Override
    public void channelUnregistered(final ChannelHandlerContext ctx) throws Exception {
        logger.info("channelUnregistered:Reconnect");
        final EventLoopGroup loop = ctx.channel().eventLoop();
        loop.schedule(() -> PushClient.connect(new Bootstrap(), loop), 10L, TimeUnit.SECONDS);
    }
}
